package com.moyuwanjia.utils;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;

/**
 * @author 摸鱼丸加~
 * @create 2022-07-08 17:39
 * 切面类，将其中的事务看做通知方法,也就是将当前类看做通知类
 */
@Slf4j
public class TransactionManager {
    private ConnectionUtils connectionUtils;
    //注入连接工具
    public void setConnectionUtils(ConnectionUtils connectionUtils){
        this.connectionUtils = connectionUtils;
    }

    /**
     * 开启事务，关闭自动提交
     */
    public void beginTransaction(){
        try {
            log.info("前置通知");
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public void commit(){
        try {
            log.info("后置通知");
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }

    /**
     * 事务回滚
     */
    public void rollback(){
        try {
            log.info("异常通知");
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }

    /**
     * 释放连接
     */
    public void release(){
         try {
             log.info("最终通知");
            connectionUtils.getThreadConnection().close();
            connectionUtils.removeConnection();//将线程和连接解绑
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }
}
